package com.pft.web.util;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.util.Log;

import com.pft.web.R;

import java.io.File;

/**
 * File description.
 *
 * @author lijianqing
 * @date 2018-3-26
 */

public class UpgradeManager {

    private static final String SHARED_KEY = UpgradeManager.class.getName();

    // 系统下载器下载ID
    private static final String APK_DOWNLOAD_QUEUE_ID_KEY = "apk_download_queue_id";

    private static final String TAG = "UpgradeManager";

    private static String PREFERENCE_NAME = "gtecard2";

    private static volatile UpgradeManager mInstance;

    private String showDialogVersion = "";

    private UpgradeManager() {

    }

    public static UpgradeManager getInstance() {
        if (mInstance == null) {
            synchronized (UpgradeManager.class) {
                if (mInstance == null) {
                    mInstance = new UpgradeManager();
                }
            }
        }
        return mInstance;
    }

    public static void saveApkDownloadQueueID(String queueId) {
        Log.d(TAG, "saveApkDownloadQueueID: 存储downloadId");
        saveShared(APK_DOWNLOAD_QUEUE_ID_KEY, queueId);
    }

    public static String getApkDownloadQueueID() {
        return getShared(APK_DOWNLOAD_QUEUE_ID_KEY);
    }


    private static void saveShared(final String key, final String value) {
        SharedPreferences preferences = Utils.getContext().getSharedPreferences(SHARED_KEY, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(key, value);
        editor.apply();
    }

    private static String getShared(final String key) {
        SharedPreferences preferences = Utils.getContext().getSharedPreferences(SHARED_KEY, Context.MODE_PRIVATE);
        return preferences.getString(key, "");
    }


    /**
     * 判断下载管理器是否可用
     */
    private boolean isDownloadManagerAvailable(Context context) {
        try {
            final int state = context.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");
            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
    }

    public static void upgradeForWebPage(final Context context, final String url) {
        Intent intent = IntentUtils.getChooserIntent(IntentUtils.getViewIntent(url), "请选择将要打开的应用");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static long upgradeForDownloadManager(final Context context, final String url) {
        FileUtils.deleteFile(FileManager.getInstallApkFile(context).getParentFile());
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.allowScanningByMediaScanner();
        request.setTitle(context.getString(R.string.app_name));
        request.setDestinationUri(Uri.fromFile(FileManager.getInstallApkFile(context)));
        request.setVisibleInDownloadsUi(true);

        long id = downloadManager.enqueue(request);
        saveApkDownloadQueueID(String.valueOf(id));
        return id;

    }

    /**
     * 通过隐式意图调用系统安装程序安装APK
     */
    public static synchronized void installApp(final Context context) {
        final File file = FileManager.getInstallApkFile(context);

        if (file == null || !file.exists()) return;
        final Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) {
            //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            final Uri apkUri = FileProvider.getUriForFile(context, "com.pft.web.provider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            final Uri apkUri = Uri.fromFile(file);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

}
